package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.hermes.app.flow.runtime.dto.domainevent.WorkItemCmd;
import com.authine.hermes.app.flow.runtime.dto.domainmodel.AttachmentModel;
import com.authine.hermes.app.launcher.cmd.Attachment;
import com.authine.hermes.app.launcher.config.annotation.OverrideEnabled;
import com.authine.hermes.app.launcher.service.WorkflowService;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.BizObjectDTO;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Nonnull;
import java.util.*;

@Slf4j
@OverrideEnabled
//@Service(value="PurhaseWorkflowService")
public class PurhaseWorkflowService extends WorkflowService {
    private final JdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(JdbcTemplate.class);

    @Override
    public SingleResponse<String> submitWorkItem(BO bo, @Nonnull String workItemId, boolean agree, String content, List<Attachment> resources) {
       log.info("####PurhaseWorkflowService.submitWorkItem bo::{},###workItemId::{},###content::{},###resources::{}", JSON.toJSONString(bo),workItemId,content,JSON.toJSONString(resources));

        List<AttachmentModel> attachmentModels = this.getAttachmentModels(resources);
        WorkItemCmd cmd = new WorkItemCmd();
        cmd.setWorkItemId(workItemId);
        cmd.setAgree(agree);
        cmd.setBizObjectDTO(this.addDto(bo));
        cmd.setContent(content);
        cmd.setResources(attachmentModels);
        SingleResponse<String> response = this.workflowRuntimeService.submitWorkItem(cmd);
        //新建线程并执行任务类
        new Thread(() -> {
            updateGoodsPurchase(workItemId,bo,content);
        }).start();
        return response;
    }
    public void updateGoodsPurchase(String workItemId,BO bo,String content){
        String sql ="select fi.*,ins.bizObjectId as bizObjectId from commoditymaterials.biz_workitem_finished fi left join commoditymaterials.biz_workflow_instance ins on fi.instanceId=ins.id where fi.id='"+workItemId+"'";
        List<Map<String, Object>> workItemList = jdbcTemplate.queryForList(sql);
        String activityCode = null;
        String workflowCode = null;
        String bizObjectId = null;
        if (CollectionUtils.isNotEmpty(workItemList)){
            log.info("###workItemList::{}",workItemList);
            activityCode=workItemList.get(0).get("activityCode").toString();
            workflowCode=workItemList.get(0).get("workflowCode").toString();
            bizObjectId=workItemList.get(0).get("bizObjectId").toString();
        }
        log.info("###activityCode::{}，###workflowCode::{}",activityCode,workflowCode);
        if ("calibration_approval_flow".equals(workflowCode)&&"Activity3".equals(activityCode)){
            log.info("############bizObjectId::{}",bizObjectId);
            String costCenterId = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).selectField("cost_center_id")
                    .eq("id", bizObjectId)
                    .queryForPOJO(String.class);
            log.info("############costCenterId::{}",costCenterId);
            String updateSql = "update operation1center.i_operation1center_t_cost_center set name='"+content+"' where id='"+costCenterId+"'";
            int update = jdbcTemplate.update(updateSql);
            log.info("###update::{}",update);
        }
        if ("calibration_approval_flow".equals(workflowCode)&&"Activity5".equals(activityCode)){
            log.info("############bizObjectId::{}",bizObjectId);
            int update = JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE).putFieldAndVal("client_purchase_request", content)
                    .eq("id", bizObjectId)
                    .update();
        }
    }

    private List<AttachmentModel> getAttachmentModels(List<Attachment> resources) {
        List<AttachmentModel> attachmentModels = new ArrayList();
        if (resources != null) {
            Iterator var3 = resources.iterator();

            while(var3.hasNext()) {
                Attachment resource = (Attachment)var3.next();
                AttachmentModel attachmentModel = new AttachmentModel();
                BeanUtils.copyProperties(resource, attachmentModel);
                attachmentModels.add(attachmentModel);
            }
        }

        return attachmentModels;
    }

    private BizObjectDTO addDto(BO bo) {
        if (bo == null) {
            return null;
        } else {
            BizObjectDTO bizObjectDTO = new BizObjectDTO();
            bizObjectDTO.setData(bo.getData());
            bizObjectDTO.setBizObjectId(bo.getBizObjectId());
            bizObjectDTO.setSchemaCode(bo.getSchemaCode());
            return bizObjectDTO;
        }
    }
}
